package com.defysoft.waukids.album;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseFragment;
import com.defysoft.waukids.Custom_Data_Type.Album_Main_List;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.defysoft.waukids.main.Main_MainFrame;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Album_Main_F extends BaseFragment {
	View view;
	GridView listView;

	ImageView writeview;
	Album_Main_Adapter adapter;
	ArrayList<Album_Main_List> list;
	TextView nodata;
	private final int SUCCESSGETPLUSLIST = 7;
	private final int STARTDETAIL = 8;
	private final int NODATA = 9;
	private final int SUCCESSGETLIST = 10;
	private final int NODATA_PLUS = 6;
	DisplayImageOptions options;
	ImageLoader imageLoader;

	Calendar calendar;
	int rank = 0;
	int selectCode = 0;
	long now = System.currentTimeMillis();
	Date date = new Date(now);
	Sqlite_Connect sc;
	SimpleDateFormat CurYearFormat;
	SimpleDateFormat CurMonthFormat ;
	SimpleDateFormat CurDayFormat ;
	SimpleDateFormat CurHourFormat ;
	SimpleDateFormat CurMinuteFormat ;
	SimpleDateFormat CurSecondFormat ;
	int count = 0;
	boolean ListViewLock;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.album_main_fragment, null);
		setStartData();

		return view;
	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		CurYearFormat = new SimpleDateFormat("yyyy"); 
		CurMonthFormat = new SimpleDateFormat("MM");  
		CurDayFormat = new SimpleDateFormat("dd");    
		CurHourFormat = new SimpleDateFormat("HH");   
		CurMinuteFormat = new SimpleDateFormat("mm"); 
		CurSecondFormat = new SimpleDateFormat("ss"); 
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getActivity()).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app

				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
		imageLoader = ImageLoader.getInstance();
		imageLoader.clearMemoryCache();
		imageLoader.clearDiskCache();

		options = new DisplayImageOptions.Builder().cacheInMemory(true)
		.imageScaleType(ImageScaleType.EXACTLY) 
		.cacheOnDisk(true).considerExifParams(true).build();
		rank = Integer.parseInt(((Main_MainFrame) getActivity()).member.Rank);
		sc = ((Main_MainFrame) getActivity()).sqlite_Connect;
		writeview = (ImageView) view.findViewById(R.id.album_main_item_write);
		if (rank == 1 || rank == 2) {
			writeview.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
					  ((Main_MainFrame) getActivity()).startForActivity(
					  START_ALBUM, new Intent(getActivity(),
					  Album_Main_Write.class));
					 
				}
			});

		} else {
			writeview.setVisibility(View.GONE);
		}

		nodata = (TextView) view.findViewById(R.id.album_main_item_nodata);
		listView = (GridView) view.findViewById(R.id.album_main_item_list);
		nodata.setVisibility(View.GONE);
		startNetwork(1);
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				switch (cho) {
				case 1:
					mainThread();
					break;
				case 2:
					subThread();
					break;
				case 3:
					plusThread();
					break;
				}
			}
		});
		firstThread.start();

	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			listView.setVisibility(View.VISIBLE);
			((Main_MainFrame)getActivity()).sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"ALBUM_MAIN_F", ((Main_MainFrame)getActivity()).member.Email);
			break;
		case NODATA:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			listView.setVisibility(View.GONE);
			nodata.setVisibility(View.VISIBLE);
			break;
		case NODATA_PLUS:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(getActivity(), ((String)_message.obj), Toast.LENGTH_LONG).show();
			break;
		case SUCCESSGETLIST:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			nodata.setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
			adapter = new Album_Main_Adapter();
			listView.setAdapter(adapter);
			listView.setOnScrollListener(new OnScrollListener() {

				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub

					int lastItem = totalItemCount - visibleItemCount;
					if (firstVisibleItem >= lastItem && totalItemCount != 0
							&& ListViewLock == false) {
						if (list.size() < count) {
							ListViewLock = true;
							startNetwork(3);
						}
					}
				}
			});
			break;
		case STARTDETAIL:

			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			adapter.notifyDataSetChanged();
			
			 ((Main_MainFrame) getActivity()).startForActivity(START_ALBUM,
			 new Intent(getActivity(), AlbumDetailActivity.class)
			 .putExtra("PK_Alb_Code", list.get(selectCode).PK_Alb_Code));
			 
			break;
		case SUCCESSGETPLUSLIST:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			adapter.notifyDataSetChanged();
			ListViewLock = false;
			break;
		}
	}

	public void mainThread() {
		String msg = "";
		JSONObject jsonObject;
		try {
			if (rank == 1) {
				jsonObject = new JSONObject(
						publicHttpCallback(
								HTTP_URL,
								"code="
										+ CODE_ALBUM_MAIN_GETLIST
										+ "&sth="
										+ ((Main_MainFrame) getActivity()).member.School));
			} else {
				jsonObject = new JSONObject(
						publicHttpCallback(
								HTTP_URL,
								"code="
										+ CODE_ALBUM_MAIN_GETLIST
										+ "&sth="
										+ ((Main_MainFrame) getActivity()).member.School
										+ "&class="
										+ ((Main_MainFrame) getActivity()).member.Class));
			}
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				count = Integer.parseInt(jsonObject.getString("count"));
				list = JsonParser.Album_Main_List_Parser(msg);
				onNetworkCallback(SUCCESSGETLIST, "");
			} else {
				onNetworkCallback(NODATA, "");
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where mainThread()");
		}
		;
	}

	public void subThread() {
		sc.delete_New_Photo(Integer.parseInt(list.get(selectCode).PK_Alb_Code));
		if (rank == 3) {
			//새로운앨범 sqlite에서 삭제
			if (sc.check_Photo(
					Integer.parseInt(list.get(selectCode).PK_Alb_Code),
					Integer.parseInt(((Main_MainFrame) getActivity()).student.Code))) {
				onNetworkCallback(STARTDETAIL, "");
			} else {
				try {
					JSONObject jsonObject = new JSONObject(
							publicHttpCallback(
									HTTP_URL,
									"code="
											+ CODE_ALBUM_MAIN_UPRATE
											+ "&pk="
											+ list.get(selectCode).PK_Alb_Code
											+ "&uprate="
											+ 1
											+ "&email="
											+ ((Main_MainFrame) getActivity()).member.Email));
					if (jsonObject.getBoolean("success")) {
						//조회수 추가
						sc.insert_Photo(
								Integer.parseInt(list.get(selectCode).PK_Alb_Code),
								Integer.parseInt(((Main_MainFrame) getActivity()).student.Code));
						list.get(selectCode).Alb_Rate = (Integer.parseInt(list
								.get(selectCode).Alb_Rate) + 1) + "";

						onNetworkCallback(STARTDETAIL, "");
					} else {
						onNetworkCallback(STARTDETAIL, "");
					}
				} catch (Exception e) {
					onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where subThread()");
				}
			}
		} else {
			onNetworkCallback(STARTDETAIL, "");
		}
	}

	public void plusThread() {
		String msg = "";
		JSONObject jsonObject;
		try {
			if (rank == 1) {
				jsonObject = new JSONObject(
						publicHttpCallback(
								HTTP_URL,
								"code="
										+ CODE_ALBUM_MAIN_GETPLUSLIST
										+ "&sth="
										+ (((Main_MainFrame) getActivity()).member.School)
										+ "&pk="
										+ list.get(list.size() - 1).PK_Alb_Code));
			} else {
				jsonObject = new JSONObject(
						publicHttpCallback(
								HTTP_URL,
								"code="
										+ CODE_ALBUM_MAIN_GETPLUSLIST
										+ "&sth="
										+ (((Main_MainFrame) getActivity()).member.School)
										+ "&pk="
										+ list.get(list.size() - 1).PK_Alb_Code
										+ "&class="
										+ ((Main_MainFrame) getActivity()).member.Class));
			}
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				list.addAll(JsonParser.Album_Main_List_Parser(msg));
				onNetworkCallback(SUCCESSGETPLUSLIST, "");
			} else {
				onNetworkCallback(NODATA_PLUS, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where plusThread()");
		}
		;
	}

	class Album_Main_Adapter extends ArrayAdapter<String> {

		public Album_Main_Adapter() {
			super(getActivity(), 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			Album_Main_Holder holder;
			final int pos = position;
			if (convertView == null) {
				convertView = getActivity().getLayoutInflater().inflate(
						R.layout.album_main_fragment_item, null);
				holder = new Album_Main_Holder();
				holder.day = (TextView) convertView
						.findViewById(R.id.album_main_item_time);
				holder.name = (TextView) convertView
						.findViewById(R.id.album_main_item_name);
				holder.school = (TextView) convertView
						.findViewById(R.id.album_main_item_school);
				holder.img = (ImageView) convertView
						.findViewById(R.id.album_main_fragment_img);
				holder.iv_new = (ImageView)convertView
						.findViewById(R.id.album_main_item_new);
				int width = ((listView.getWidth()) / 2- ((int) getResources().getDimension(R.dimen.albumgridmarjin) ));
				int height = ((listView.getWidth()) / 2- ((int) getResources().getDimension(R.dimen.albumgridmarjin) ));
				holder.rl = (RelativeLayout) convertView
						.findViewById(R.id.album_main_fragment_ll);
				holder.rl.setLayoutParams(new LinearLayout.LayoutParams(
						width, height));

				convertView.setTag(holder);
			} else {
				holder = (Album_Main_Holder) convertView.getTag();
			}
			
			//새로운글 체크
			if (sc.check_New_Photo(Integer.parseInt(list.get(pos).PK_Alb_Code))) {
				holder.iv_new.setVisibility(View.VISIBLE);
			} else {
				holder.iv_new.setVisibility(View.GONE);
			}
			
			holder.school
			.setText(list.get(position).Alb_Writer);
			
			/*if (list.get(position).Teacher.equals("null")
					|| list.get(position).Teacher.equals("")) {
				holder.school
						.setText(((Main_MainFrame) getActivity()).school.Name);
			} else {
				holder.school.setText(list.get(position).Teacher);
			}*/
			
			holder.name.setText(list.get(position).Alb_Name);
			
			holder.img.setImageResource(0xffeeeeee);
			
			holder.day.setText(timeCalculation(list.get(position).Alb_Date));
			if (list.get(pos).photo.size()>0) {
				imageLoader.displayImage(HTTP_URL_ALBUMPHOTO
						+ list.get(pos).photo.get(0).Alb_Pho_IMG,
						holder.img, options, null);
			}else {
				imageLoader.displayImage("",
						holder.img, options, null);
			}
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					selectCode = pos;
					startNetwork(2);
				}
			});
			return convertView;
		}

	}

	protected String timeCalculation(String data) {
		// 시간 계산기. split
		String notice_date = data;
		String result = "";
		// 1.공지사항 시간.
		String not_date = notice_date.split(" ")[0];
		String not_time = notice_date.split(" ")[1];
		// 일월년 분할.
		int not_year = Integer.parseInt(not_date.split("-")[0]);
		int not_month = Integer.parseInt(not_date.split("-")[1]);
		int not_day = Integer.parseInt(not_date.split("-")[2]);
		// 시분초 분할.
		int not_hour = Integer.parseInt(not_time.split(":")[0]);
		int not_minute = Integer.parseInt(not_time.split(":")[1]);
		int not_second = Integer.parseInt(not_time.split(":")[2]);

		// 2. 현재날짜시간
		int now_year = Integer.parseInt(CurYearFormat.format(date));
		int now_month = Integer.parseInt(CurMonthFormat.format(date));
		int now_day = Integer.parseInt(CurDayFormat.format(date));
		int now_hour = Integer.parseInt(CurHourFormat.format(date));
		int now_minute = Integer.parseInt(CurMinuteFormat.format(date));
		int now_second = Integer.parseInt(CurSecondFormat.format(date));

		// 3. 계산기 시작.
		if (not_year < now_year) {
			result = not_date;
		} else if (not_month < now_month) {
			int a = (now_month - not_month);
			result = a + " 개월 전";
		} else if (not_day < now_day) {
			int aa = (now_day - not_day);
			result = aa + " 일 전";
		} else if (not_hour < now_hour) {
			int aaa = (now_hour - not_hour);
			result = aaa + " 시간 전";
		} else if (not_minute < now_minute) {
			int aaaa = (now_minute - not_minute);
			result = aaaa + " 분 전";
		} else if (not_minute == now_minute) {
			result = "방금 전";
		} else{
			result = "방금 전";
		}
		// 계산기 끝.
		/** 하단 미확인부모, 스탬프3개 */
		return result;
	}

	class Album_Main_Holder {
		TextView name;
		TextView school;
		TextView day;
		ImageView img;
		RelativeLayout rl;
		ImageView iv_new;
	}

}
